<template>
  <div class="head-container">
    <el-input v-model="dirName" class="mb-20px" clearable placeholder="请输入目录名称">
      <template #prefix>
        <Icon icon="ep:search" />
      </template>
    </el-input>
  </div>
  <div class="head-container">
    <div
      class="flex flex-items-center font-size-16px mb-5px cursor-pointer"
      @click="openForm('create')"
    >
      <Icon :icon="'ep:folder-add'" /> <el-button link> 添加分类</el-button>
    </div>
    <el-tree
      ref="treeRef"
      :data="dirList"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      :props="defaultProps"
      default-expand-all
      highlight-current
      node-key="typeId"
      @node-click="handleNodeClick"
    >
      <template #default="{ node }">
        <div class="flex flex-items-center flex-justify-between w-100%">
          <div class="flex flex-items-center h-48px">
            <Icon :icon="'svg-icon:file'" /> <span class="ml-5px">{{ node.label }}</span></div
          >
          <div class="flex flex-items-center">
            <el-dropdown @command="handleCommand">
              <Icon :icon="'ep:more-filled'" />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="['edit', node]">分类编辑</el-dropdown-item>
                  <el-dropdown-item :command="['delete', node]">分类删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>
    </el-tree>
  </div>
  <!-- 添加或修改目录 -->
  <DirForm ref="formRef" @success="getTree" />
</template>

<script lang="ts" setup>
import { ElTree } from 'element-plus'
import * as FileApi from '@/api/infra/file'

import { handleTree } from '@/utils/tree'
import DirForm from './DirForm.vue'

defineOptions({ name: 'SystemUserDeptTree' })
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const defaultProps = {
  children: 'children',
  label: 'typeName',
  value: 'typeId',
  isLeaf: 'leaf',
  multiple: false,
  emitPath: false // 用于 cascader 组件：在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
}

const dirName = ref('')
const dirList = ref<Tree[]>([]) // 树形结构
const treeRef = ref<InstanceType<typeof ElTree>>()

/** 获得目录树 */
const getTree = async () => {
  const res = await FileApi.getSimpleDirList()
  dirList.value = []
  dirList.value.push(...handleTree(res, 'typeId'))
}

/** 基于名字过滤 */
const filterNode = (name: string, data: Tree) => {
  if (!name) return true
  return data.name.includes(name)
}

/** 处理目录被点击 */
const handleNodeClick = async (row: { [key: string]: any }) => {
  emits('node-click', row)
}
const emits = defineEmits(['node-click', 'node-add', 'node-update', 'node-delete'])
/** 操作:添加 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}
/** 操作：编辑、删除 */
const handleCommand = async (data) => {
  const type = data[0]
  const node = data[1]
  if (type === 'delete') {
    handleDelete(node.data.typeId)
  } else if (type === 'edit') {
    openForm('update', node.data.typeId)
  }
}
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await FileApi.deleteDir(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getTree()
  } catch {}
}

/** 监听dirName */
watch(dirName, (val) => {
  treeRef.value!.filter(val)
})

/** 初始化 */
onMounted(async () => {
  await getTree()
})
</script>
